import { setToken, getToken, removeToken, setTimeStamp } from '@/utils/auth'
// 导入封装的请求api
import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { resetRouter } from '@/router'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    setToken(state, data) {
      state.token = data
      setToken(data)
    },
    setUserInfo(state, data) {
      state.userInfo = data
    },
    removeToken(state) {
      state.token = ''
      removeToken()
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async login(store, data) {
      try {
        const res = await login(data)
        store.commit('setToken', res)
        setTimeStamp()
      } catch (err) {
        console.log('catch捕获错误', err)
      }
    },
    async getUserInfo(store) {
      const userSimple = await getUserInfo()
      const userDetail = await getUserDetailById(userSimple.userId)
      // console.log('获取用户简单信息', userSimple)
      // console.log('获取用户详细信息', userDetail)
      const res = {
        ...userSimple,
        ...userDetail
      }
      // console.log('用户信息合并', res)
      store.commit('setUserInfo', res)
      return res
    },
    logout(store) {
      store.commit('removeToken')
      store.commit('removeUserInfo')
      // 清理路由信息
      resetRouter()
      store.commit('permission/setRoutes', [], { root: true })
    }
  }
}
